package com.neuedu.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.neuedu.common.Const;
import com.neuedu.common.JSONData;
import com.neuedu.pojo.UserInfo;
import com.neuedu.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/pay/")
public class PayContoller {

    @Autowired
    private PayService payService;

    @RequestMapping(value = "pay",method = RequestMethod.POST)
    @ResponseBody
    public JSONData pay(HttpSession session, Long orderNo, HttpServletRequest request){
        //1、判断用户是否登录
        UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENT_USERINFO);
        if(userInfo==null){
            return JSONData.buildError("您未登录，请先登录");
        }
        //service
        String path = request.getSession().getServletContext().getRealPath("upload");
        JSONData data = payService.pay(userInfo.getId(), orderNo, path);
        return data;
    }
    //-处理服务器返回的处理结果:request
    @RequestMapping("callback")
    public JSONData payCallBack(HttpSession session,HttpServletRequest request){

        Map<String,String> map = new HashMap<String, String>();
        //-获取request中的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keys = parameterMap.keySet();
        Iterator<String> iterator = keys.iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            String[] vals = parameterMap.get(key);
            String val_str = "";
            for(int i=0;i<vals.length;i++){
                val_str = i==vals.length-1?val_str+vals[i]:val_str+vals[i]+",";
            }
            map.put(key,val_str);
        }
        //-查看返回的信息
        System.out.println("支付宝签名sign："+map.get("sign"));
        System.out.println("交易状态trade_status："+map.get("trade_status"));

        //-验证回调的正确性
        //map.remove("sign_type");
        try {
            boolean flag = AlipaySignature.rsaCheckV2(map, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
            if(!flag){
                return JSONData.buildError("非法请求，验证不通过");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //-修改支付信息：
        UserInfo userInfo = (UserInfo) session.getAttribute(Const.CURRENT_USERINFO);
        JSONData data = payService.callback(map, userInfo.getId());
        return data;
    }

    /*查看订单的支付状态*/

}
